from .serializers import *
from .FilterBackends import *
from .main import *
import logging


# Create your views here.
logger = logging.getLogger(__name__)
# =======================================


class SystemBackendLogsForUserSerializer(serializers.Serializer):
    """无序列化"""

    logdate = DateField(help_text="日期")
    level = ChoiceField(
        allow_blank=True,
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        help_text="日志级别",
        required=False,
    )
    method = ChoiceField(
        allow_blank=True,
        choices=["GET", "POST", "PUT", "PATCH", "DELETE"],
        help_text="请求方式",
        required=False,
    )
    userid = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="用户ID"
    )
    views = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="视图名称"
    )
    idx = IntegerField(min_value=0, max_value=9, default=0, help_text="文件序号")

    class Meta:
        fields = "__all__"


class SystemBackendLogsForUserViewSet(viewsets.ModelViewSet):
    __title__ = "查询后台操作日志"
    __group__ = "系统后台"
    __info__ = {"post": "查询后台操作日志"}
    __doc__ = """	
    create:
    <h4>查询后台操作日志</h4>    
    """
    http_method_names = ["post"]
    authentication_classes = [] if settings.DEBUG else [MyJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [MyPermissions]
    serializer_class = SystemBackendLogsForUserSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # print(serializer.data)
        data = serializer.data.copy()
        if not data.get("idx"):
            log_file = "/opt/logs/error_oplog.log"
        else:
            log_file = f'/opt/logs/error_oplog.log.{data.get("idx")}'

        search = (
            f'^{data.get("logdate")}'
            + "[[:space:]][[:digit:]]\{1,2\}:[[:digit:]]\{1,2\}:[[:digit:]]\{1,2\}"
        )
        if data.get("level"):
            search += f'.*[{data.get("level")}]'
        if data.get("userid"):
            search += f'.*[{data.get("userid")}]'
        if data.get("method"):
            search += f'.*[{data.get("method")}]'
        if data.get("views"):
            search += f'.*[{data.get("views")}]'
        search += ".*\n&"
        # print(search)
        import subprocess

        cmd = f'cat {log_file} | grep "{search}"'
        # print(cmd)
        ret = subprocess.run(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
        )
        # print(ret.stdout)
        res = ret.stdout.split("\n")
        return Response({"rescode": 200, "resmsg": res[:-1]})
